package com.kwin.rpcclient.scan;

import java.lang.reflect.Proxy;
import java.util.Arrays;

import com.kwin.rpcclient.holder.ConnManage;
import com.kwin.rpcclient.holder.RpcClientHolder;
import com.kwin.rpccommon.annotation.RpcClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author : wangkai
 * @version V1.0
 * @Package com.kwin.rpc.config.rpc
 * @Description:
 * @date 2021年06月22日 15:20
 **/
@Slf4j
public class RpcFactoryBean<T> implements FactoryBean<T> {
    
    private Class<T> rpcInterface;
    
//    RpcFactory<T> factory = new RpcFactory<>();
    
//    @Autowired
    private RpcFactory<T> factory = new RpcFactory<>();
    
    public RpcFactoryBean() {
    }
    
    public RpcFactoryBean(Class<T> rpcInterface) {
        this.rpcInterface = rpcInterface;
    
        RpcClient rpcClient = rpcInterface.getAnnotation(RpcClient.class);
        log.error("value is {}, url is {}", rpcClient.value(), rpcClient.url());
        if(!RpcClientHolder.lazy) {
            ConnManage.updateConnServer(rpcClient.value(), Arrays.asList(rpcClient.url().clone()));
        }
        
    }
    
    @Override
    public T getObject() throws Exception {
        return getRpc();
    }
    
    @Override
    public Class<?> getObjectType() {
        return this.rpcInterface;
    }
    
    @Override
    public boolean isSingleton() {
        return true;
    }
    
    private void initRpcClient() {
    
    }
    
    public <T> T getRpc() {
        return (T) Proxy.newProxyInstance(rpcInterface.getClassLoader(), new Class[] { rpcInterface },factory);
    }
}
